//
//  ShoppingCartViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/24.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import MJRefresh
import DZNEmptyDataSet

/// 购物车

class ShoppingCartViewController: BaseViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var dataArray = [SiteGoodsModel]()
    
    var seleGoodsIndexArray = NSMutableArray()  // 选中商品的id
    
    var seleGoodsDic = NSMutableDictionary() // key：商品id  value：选中商品的数量
    
    @IBOutlet weak var seletedAllBtn: UIButton!
    
    @IBOutlet weak var totalLabel: UILabel!
    
    var totalPrice:Double = 0
    
    var orderId = 0
    
    var soldGoodsCount = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "购物车"
        self.tableView.backgroundColor = UIColor.backgroundColor
        self.tableView.rowHeight = 100
        self.tableView.emptyDataSetSource = self
        self.tableView.emptyDataSetDelegate = self
        
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 10))
        header.backgroundColor = UIColor.backgroundColor
        self.tableView.tableHeaderView = header
        
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.getCartList()
        })
        
        if Utils.isLogined() {
            PKhud.show()
            getCartList()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateList), name: NSNotification.Name(rawValue: "logined"), object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(submitOrderSuccess), name: NSNotification.Name(rawValue: "submitOrder"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(updateListGoodsCount), name: NSNotification.Name(rawValue: "updateListGoods"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        self.navigationController?.navigationBar.isTranslucent = false
        if !Utils.isLogined(){
            self.dataArray.removeAll()
            self.tableView.reloadData()
        }
    }
    
    @objc func updateListGoodsCount(notification: Notification){
        guard let userInfo = notification.object else {
            return
        }
        let goodsID = (userInfo as! postParameters)["goodsID"] as! Int
        let keys = self.seleGoodsDic.allKeys as NSArray
        if keys.contains("\(goodsID)"){
            let value = self.seleGoodsDic.object(forKey: "\(goodsID)") as! Int
            self.seleGoodsDic.setValue(value + 1, forKey: "\(goodsID)")
        }
        
        Utils.DispatchAfter(after: 2) {
            self.getCartList()
        }
    }
    
    @objc func updateList(){
        self.getCartList()
    }
    
//    @objc func submitOrderSuccess(){
//        self.seleGoodsIndexArray.removeAllObjects()
//        self.seleGoodsDic.removeAllObjects()
//        self.getCartList()
//    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func getCartList(){
        self.soldGoodsCount = 0
        HttpRequest.requestData(.post, URLString: Api.cartList.rawValue, parameters: ["orderId":self.orderId]) { (result) in
            PKhud.hiden()
            self.tableView.mj_header.endRefreshing()
            if result["msg"] as! String == "success"{
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel] {
                    self.dataArray = array
                    DispatchQueue.global().async {
                        let keys = self.seleGoodsDic.allKeys as NSArray
                        for model in array {
                            
                            if model.state != 0 {
                                self.soldGoodsCount = self.soldGoodsCount + 1
                            }else{
//                                 self.seleGoodsIndexArray.add(model) // 默认全选商品
                            }
                            if !keys.contains("\(model.id)"){
                                self.seleGoodsDic.setValue(1, forKey: "\(model.id)")
                            }
                        }
                        Utils.dispatchMainQueue {
                            self.checkTotalPrice()
                            self.tableView.reloadData()
                        }
                    }
                }
            }else{
                if result["isLogin"] != nil {
                    PKhud.showText(text: result["data"] as! String)
                    Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: true)
                }
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:全选
    @IBAction func seleAllMethod(_ sender: UIButton) {
        if sender.isSelected == false {
            self.seleGoodsIndexArray.removeAllObjects()
            for model in self.dataArray {
                if model.state == 0 {
                    self.seleGoodsIndexArray.add(model)
                }
            }
        }else{
            self.seleGoodsIndexArray.removeAllObjects()
        }
        self.checkTotalPrice()
        self.tableView.reloadData()
    }
    
    
    // MARK:结算
    @IBAction func settlementMethod(_ sender: UIButton) {
        
        guard self.seleGoodsIndexArray.count != 0 else {
            PKhud.showText(text: "您还未选择任何商品~")
            return
        }
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ConfirmOrderViewController") as! ConfirmOrderViewController
        ctrl.hidesBottomBarWhenPushed = true
        ctrl.seleGoodsDic = self.seleGoodsDic
        ctrl.seleGoodsIndexArray = self.seleGoodsIndexArray
        ctrl.backSeleGoods = { [weak self] (dic) in
            self?.seleGoodsDic.removeAllObjects()
            self?.seleGoodsIndexArray.removeAllObjects()
            self?.getCartList()
        }
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    
    func checkTotalPrice(){
        
        if  self.dataArray.count != 0 {
            if self.seleGoodsIndexArray.count == self.dataArray.count - self.soldGoodsCount {
                self.seletedAllBtn.isSelected = true
            }else{
                self.seletedAllBtn.isSelected = false
            }
        }else{
            self.seletedAllBtn.isSelected = false
        }
        
        guard self.seleGoodsIndexArray.count != 0 else {
            self.totalLabel.text = "合计："
            return
        }
        var price:Double = 0
        for model in self.seleGoodsIndexArray {
            let count = self.seleGoodsDic.object(forKey: "\((model as! SiteGoodsModel).id)") as! Int
            var currentPrice:Double = 0
            if (model as! SiteGoodsModel).isDiscount == 1 {
                currentPrice = (model as! SiteGoodsModel).discountMoney
            }else if (model as! SiteGoodsModel).isActivity == 1 {
                currentPrice = (model as! SiteGoodsModel).activityMoney
            }else if (model as! SiteGoodsModel).peddlersPrice != nil {
                currentPrice = Double.init(((model as! SiteGoodsModel).peddlersPrice)!)!
            }else{
                currentPrice = (model as! SiteGoodsModel).price
            }
            price = price + Double(count) * currentPrice
        }
        
        var attribute = NSMutableAttributedString.init(string: "合计：￥" + "\(price)")
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], range: NSString.init(string: "合计：￥" + "\(price)").range(of: "￥" + "\(price)"))
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 17)], range: NSString.init(string: "合计：￥" + "\(price)").range(of: "\(price)".getPriceInteger()))
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: "合计：￥" + "\(price)").range(of: "￥" + "\(price)"))
        self.totalLabel.attributedText = attribute
    }
    

}

extension ShoppingCartViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingCartTableViewCell") as! ShoppingCartTableViewCell
        let model = self.dataArray[indexPath.row]
        cell.goodsCount = 1
        if self.seleGoodsDic.object(forKey: "\(model.id)") != nil {
            cell.goodsCount = self.seleGoodsDic.object(forKey: "\(model.id)") as! Int
        }
        cell.seleBtn.isSelected = false
        cell.reload(withModel: model)
        if self.seleGoodsDic.object(forKey:"\(model.id)") != nil {
            cell.countLabel.text = "\(self.seleGoodsDic.object(forKey:"\(model.id)") as! Int )"
        }else{
            cell.countLabel.text = "1"
        }
        
        for obj in self.seleGoodsIndexArray {
            if (obj as! SiteGoodsModel).id == model.id && model.state != 1 {
                cell.seleBtn.isSelected = true
                break
            }
        }
        
        cell.backGoodsCount = { [weak self] (count) in
            self?.seleGoodsDic.setValue(count, forKey: "\(model.id)")
            self?.checkTotalPrice()
        }
        
        cell.seleClosure = { [weak self] (value) in
            if value {
                self?.seleGoodsIndexArray.add(model)
            }else{
                for obj in (self?.seleGoodsIndexArray)! {
                    if (obj as! SiteGoodsModel).id == model.id {
                        self?.seleGoodsIndexArray.remove(obj)
                        break
                    }
                }
            }
            self?.checkTotalPrice()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.dataArray[indexPath.row]
        if model.state != 0 {
            PKhud.showText(text: "该商品已下架~")
            return
        }
        
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
        ctrl.hidesBottomBarWhenPushed = true
        ctrl.goodsID = model.id
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        self.deleGoodsItem(goodsID: self.dataArray[indexPath.row].id) { [weak self](flag) in
            if flag {
                self?.seleGoodsDic.removeObject(forKey: "\((self?.dataArray[indexPath.row].id)!)")
                for model in (self?.seleGoodsIndexArray)! {
                    if (model as! SiteGoodsModel).id == self?.dataArray[indexPath.row].id {
                        self?.seleGoodsIndexArray.remove(model)
                        break
                    }
                }
                self?.checkTotalPrice()
                self?.dataArray.remove(at: indexPath.row)
                self?.tableView.deleteRows(at: [indexPath], with: .fade)
                self?.tableView.reloadData()
            }
        }
    }
    
//    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//        let action =  UITableViewRowAction.init(style: UITableViewRowActionStyle.default, title: "删除啊哈哈哈") { (action, indexPath) in
//            print("action1")
//        }
//
//        let action1 =  UITableViewRowAction.init(style: UITableViewRowActionStyle.default, title: "删除啊哈哈哈1111") { (action, indexPath) in
//            print("action222")
//        }
//
//        return [action,action1]
//
//    }
    
    @available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleAction = UIContextualAction.init(style: .destructive, title: "") { (action, sourceView, closure:@escaping (Bool)->Void) in
            self.deleGoodsItem(goodsID: self.dataArray[indexPath.row].id, closure: {(flag) in
                if flag {
                    self.dataArray.remove(at: indexPath.row)
                    self.tableView.reloadData()
                }
                closure(flag)
            })
        }
        deleAction.image = UIImage.init(named: "icon_delete_3")
        deleAction.backgroundColor = UIColor.init(hexColor: "000000")
        return UISwipeActionsConfiguration.init(actions: [deleAction])
    }
    
    func deleGoodsItem(goodsID:Int,closure:@escaping (Bool)->Void){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.CartDelete.rawValue, parameters: ["goodsId":goodsID]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                self.seleGoodsDic.removeObject(forKey: "\(goodsID)")
                for model in self.seleGoodsIndexArray {
                    if (model as! SiteGoodsModel).id == goodsID {
                        self.seleGoodsIndexArray.remove(model)
                        break
                    }
                }
                self.checkTotalPrice()
                closure(true)
            }else{
                closure(false)
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}


extension ShoppingCartViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
        
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "空空如也~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
}











